<template>
  <div>
    <h1>发表评论</h1>
    <hr>
    <textarea cols="10" rows="5" noresize placeholder="请输入评论内容" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>
    
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item,index) in comments" :key="index">
        <div class="cmt-title">
         <p>第{{index+1}}楼&nbsp;&nbsp;用户名:{{item.user_name}} 发表时间：{{item.add_time | dateFormat}}</p>
        </div>
        <div class="cmt-body">{{item.content}}</div>
      </div>
    </div>

    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
  </div>
</template>
<script>
import { Toast } from "mint-ui";
export default {
  /* 涉及到父子组件的传值  id值 */
  data() {
    return {
      pageindex: 1,
      comments: [],
      msg: ""
    };
  },
  created() {
    this.getComments();
  },
  methods: {
    //获取评论
    getComments() {
      this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageindex)
        .then(result => {
          if (result.body.status === 0) {
            /* 若是直接赋值，新数据会覆盖老数据，应使用数组的concat方法进行拼接 */
            this.comments = this.comments.concat(result.body.message);
          } else {
            Toast("加载失败...");
          }
        });
    },
    //加载更多
    getMore() {
      this.pageindex++;
      /* this.pageindex增加后，再次获取评论 */
      this.getComments();
    },
    //发表评论
    postComment() {
      /* trim() 去除空格 如果直接将数据添加到comments中，再调用获取评论的方法，可能只能获取最后一页的数据，无法获取前几页的评论，所以应该手动添加一个对象unshift到comments */
      if (this.msg.trim() === "") {
        return Toast("输入内容不能为空");
      }
      this.$http
        .post("api/postcomment/" + this.$route.params.id, {
          content: this.msg.trim()
        })
        .then(result => {
          if (result.body.status === 0) {
            var cmt = {
              user_name: "匿名用户",
              add_time: Date.now(),
              content: this.msg.trim()
            };
            this.comments.unshift(cmt);
            this.msg = "";
            console.log(this.comments);
          }
        });

    }
  },
  props: ["id"]
};
</script>
<style lang="scss" scoped>
h1 {
  font-size: 20px;
  padding: 5px;
}
textarea {
  margin-top: 10px;
}
.cmt-list {
  margin-top: 10px;
  .cmt-title {
    height: 30px;
    line-height: 30px;
    background-color: #cbcbcb;
    border-radius: 5px;
    p {
      font-size: 12px;
      margin: 0 5px;
      color: #000;
    }
  }
  .cmt-body {
    padding: 5px 30px;
  }
}
</style>
